package cn.ibizlab.businesscentral.centralapi.rest;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.math.BigInteger;
import java.util.HashMap;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSONObject;
import javax.servlet.ServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.util.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PostAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import cn.ibizlab.businesscentral.centralapi.dto.*;
import cn.ibizlab.businesscentral.centralapi.mapping.*;
import cn.ibizlab.businesscentral.core.base.domain.KnowledgeArticle;
import cn.ibizlab.businesscentral.core.base.service.IKnowledgeArticleService;
import cn.ibizlab.businesscentral.core.base.filter.KnowledgeArticleSearchContext;
import cn.ibizlab.businesscentral.util.annotation.VersionCheck;

@Slf4j
@Api(tags = {"知识文章" })
@RestController("CentralApi-knowledgearticle")
@RequestMapping("")
public class KnowledgeArticleResource {

    @Autowired
    public IKnowledgeArticleService knowledgearticleService;

    @Autowired
    @Lazy
    public KnowledgeArticleMapping knowledgearticleMapping;

    @PreAuthorize("hasPermission(this.knowledgearticleMapping.toDomain(#knowledgearticledto),'iBizBusinessCentral-KnowledgeArticle-Create')")
    @ApiOperation(value = "新建知识文章", tags = {"知识文章" },  notes = "新建知识文章")
	@RequestMapping(method = RequestMethod.POST, value = "/knowledgearticles")
    public ResponseEntity<KnowledgeArticleDTO> create(@RequestBody KnowledgeArticleDTO knowledgearticledto) {
        KnowledgeArticle domain = knowledgearticleMapping.toDomain(knowledgearticledto);
		knowledgearticleService.create(domain);
        KnowledgeArticleDTO dto = knowledgearticleMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.knowledgearticleMapping.toDomain(#knowledgearticledtos),'iBizBusinessCentral-KnowledgeArticle-Create')")
    @ApiOperation(value = "批量新建知识文章", tags = {"知识文章" },  notes = "批量新建知识文章")
	@RequestMapping(method = RequestMethod.POST, value = "/knowledgearticles/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<KnowledgeArticleDTO> knowledgearticledtos) {
        knowledgearticleService.createBatch(knowledgearticleMapping.toDomain(knowledgearticledtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @VersionCheck(entity = "knowledgearticle" , versionfield = "updatedate")
    @PreAuthorize("hasPermission(this.knowledgearticleService.get(#knowledgearticle_id),'iBizBusinessCentral-KnowledgeArticle-Update')")
    @ApiOperation(value = "更新知识文章", tags = {"知识文章" },  notes = "更新知识文章")
	@RequestMapping(method = RequestMethod.PUT, value = "/knowledgearticles/{knowledgearticle_id}")
    public ResponseEntity<KnowledgeArticleDTO> update(@PathVariable("knowledgearticle_id") String knowledgearticle_id, @RequestBody KnowledgeArticleDTO knowledgearticledto) {
		KnowledgeArticle domain  = knowledgearticleMapping.toDomain(knowledgearticledto);
        domain .setKnowledgearticleid(knowledgearticle_id);
		knowledgearticleService.update(domain );
		KnowledgeArticleDTO dto = knowledgearticleMapping.toDto(domain );
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.knowledgearticleService.getKnowledgearticleByEntities(this.knowledgearticleMapping.toDomain(#knowledgearticledtos)),'iBizBusinessCentral-KnowledgeArticle-Update')")
    @ApiOperation(value = "批量更新知识文章", tags = {"知识文章" },  notes = "批量更新知识文章")
	@RequestMapping(method = RequestMethod.PUT, value = "/knowledgearticles/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<KnowledgeArticleDTO> knowledgearticledtos) {
        knowledgearticleService.updateBatch(knowledgearticleMapping.toDomain(knowledgearticledtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasPermission(this.knowledgearticleService.get(#knowledgearticle_id),'iBizBusinessCentral-KnowledgeArticle-Remove')")
    @ApiOperation(value = "删除知识文章", tags = {"知识文章" },  notes = "删除知识文章")
	@RequestMapping(method = RequestMethod.DELETE, value = "/knowledgearticles/{knowledgearticle_id}")
    public ResponseEntity<Boolean> remove(@PathVariable("knowledgearticle_id") String knowledgearticle_id) {
         return ResponseEntity.status(HttpStatus.OK).body(knowledgearticleService.remove(knowledgearticle_id));
    }

    @PreAuthorize("hasPermission(this.knowledgearticleService.getKnowledgearticleByIds(#ids),'iBizBusinessCentral-KnowledgeArticle-Remove')")
    @ApiOperation(value = "批量删除知识文章", tags = {"知识文章" },  notes = "批量删除知识文章")
	@RequestMapping(method = RequestMethod.DELETE, value = "/knowledgearticles/batch")
    public ResponseEntity<Boolean> removeBatch(@RequestBody List<String> ids) {
        knowledgearticleService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PostAuthorize("hasPermission(this.knowledgearticleMapping.toDomain(returnObject.body),'iBizBusinessCentral-KnowledgeArticle-Get')")
    @ApiOperation(value = "获取知识文章", tags = {"知识文章" },  notes = "获取知识文章")
	@RequestMapping(method = RequestMethod.GET, value = "/knowledgearticles/{knowledgearticle_id}")
    public ResponseEntity<KnowledgeArticleDTO> get(@PathVariable("knowledgearticle_id") String knowledgearticle_id) {
        KnowledgeArticle domain = knowledgearticleService.get(knowledgearticle_id);
        KnowledgeArticleDTO dto = knowledgearticleMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "获取知识文章草稿", tags = {"知识文章" },  notes = "获取知识文章草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/knowledgearticles/getdraft")
    public ResponseEntity<KnowledgeArticleDTO> getDraft() {
        return ResponseEntity.status(HttpStatus.OK).body(knowledgearticleMapping.toDto(knowledgearticleService.getDraft(new KnowledgeArticle())));
    }

    @ApiOperation(value = "检查知识文章", tags = {"知识文章" },  notes = "检查知识文章")
	@RequestMapping(method = RequestMethod.POST, value = "/knowledgearticles/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody KnowledgeArticleDTO knowledgearticledto) {
        return  ResponseEntity.status(HttpStatus.OK).body(knowledgearticleService.checkKey(knowledgearticleMapping.toDomain(knowledgearticledto)));
    }

    @PreAuthorize("hasPermission(this.knowledgearticleMapping.toDomain(#knowledgearticledto),'iBizBusinessCentral-KnowledgeArticle-Save')")
    @ApiOperation(value = "保存知识文章", tags = {"知识文章" },  notes = "保存知识文章")
	@RequestMapping(method = RequestMethod.POST, value = "/knowledgearticles/save")
    public ResponseEntity<Boolean> save(@RequestBody KnowledgeArticleDTO knowledgearticledto) {
        return ResponseEntity.status(HttpStatus.OK).body(knowledgearticleService.save(knowledgearticleMapping.toDomain(knowledgearticledto)));
    }

    @PreAuthorize("hasPermission(this.knowledgearticleMapping.toDomain(#knowledgearticledtos),'iBizBusinessCentral-KnowledgeArticle-Save')")
    @ApiOperation(value = "批量保存知识文章", tags = {"知识文章" },  notes = "批量保存知识文章")
	@RequestMapping(method = RequestMethod.POST, value = "/knowledgearticles/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<KnowledgeArticleDTO> knowledgearticledtos) {
        knowledgearticleService.saveBatch(knowledgearticleMapping.toDomain(knowledgearticledtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-KnowledgeArticle-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-KnowledgeArticle-Get')")
	@ApiOperation(value = "获取DEFAULT", tags = {"知识文章" } ,notes = "获取DEFAULT")
    @RequestMapping(method= RequestMethod.GET , value="/knowledgearticles/fetchdefault")
	public ResponseEntity<List<KnowledgeArticleDTO>> fetchDefault(KnowledgeArticleSearchContext context) {
        Page<KnowledgeArticle> domains = knowledgearticleService.searchDefault(context) ;
        List<KnowledgeArticleDTO> list = knowledgearticleMapping.toDto(domains.getContent());
        return ResponseEntity.status(HttpStatus.OK)
                .header("x-page", String.valueOf(context.getPageable().getPageNumber()))
                .header("x-per-page", String.valueOf(context.getPageable().getPageSize()))
                .header("x-total", String.valueOf(domains.getTotalElements()))
                .body(list);
	}

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-KnowledgeArticle-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-KnowledgeArticle-Get')")
	@ApiOperation(value = "查询DEFAULT", tags = {"知识文章" } ,notes = "查询DEFAULT")
    @RequestMapping(method= RequestMethod.POST , value="/knowledgearticles/searchdefault")
	public ResponseEntity<Page<KnowledgeArticleDTO>> searchDefault(@RequestBody KnowledgeArticleSearchContext context) {
        Page<KnowledgeArticle> domains = knowledgearticleService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(knowledgearticleMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
}

